package ltd.hxya.novel.search.config;

import ltd.hxya.novel.search.service.BookSearchService;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class SearchConfig {

    @Value("${novel.search.es.renew-time}")
    private Integer interval;

    @Autowired
    private BookSearchService bookSearchService;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("11.0.0.12",9200,"http" )
                )
        );
        return restHighLevelClient;
    }



    //创建定时任务，更新es中的数据
    @PostConstruct
    public void renewEs(){
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
        executor.scheduleWithFixedDelay(()->{
            try {
                bookSearchService.renewEs();
            }catch (Exception e){
                e.printStackTrace();
            }

        },0,interval, TimeUnit.MINUTES);
    }
}
